package com.fast.security;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fast.constants.CacheConstants;
import com.fast.pojo.dto.SecurityUserDTO;
import com.fast.pojo.dto.TokenDTO;
import com.fast.utils.jwt.JwtUtils;
import com.fast.utils.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.security.TokenAuthenticationFilter
 * @description: token 认证过滤器
 * @since 2024/6/30 15:09
 */
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final RedisCache redisCache;

    public TokenAuthenticationFilter(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    //把用户信息填充进securitycontext,因为:
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("request url ： {}", request.getRequestURI());

        //获取头里的Authorization
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (StrUtil.isBlank(token)) {
            //放行，权限控制交给FilterSecurityInterceptor
            filterChain.doFilter(request, response);
            return;
        }

        DecodedJWT verify = JwtUtils.verify(token);

        //解析获取token包含的用户信息
        TokenDTO tokenDTO = JwtUtils.parse(verify, TokenDTO.class);

        if (ObjectUtils.isEmpty(tokenDTO)) {

            //放行，权限控制交给FilterSecurityInterceptor
            filterChain.doFilter(request, response);
            return;

        }

        SecurityContextHolder.getContext().setAuthentication(buildAutentication(tokenDTO));

        filterChain.doFilter(request, response);
    }

    private Authentication buildAutentication(TokenDTO tokenDTO) {
        //登录成功后已经存入
        SecurityUserDTO cacheObject = redisCache.getCacheObject(CacheConstants.LOGIN_INFO_KEY + tokenDTO.getUserName(),SecurityUserDTO.class);
        if (cacheObject != null) {
            Collection<? extends GrantedAuthority> authorities = cacheObject.getAuthorities();
            return new UsernamePasswordAuthenticationToken(cacheObject, null, authorities);
        }
        return null;
    }
}
